package com.maigao.util.context;

import com.maigao.util.context.ip.IP;
import com.maigao.util.context.user.User;
import org.springframework.lang.Nullable;


/**
 * @author awei
 * @description:
 * @date 2022/5/15 10:00 下午
 */
public abstract class Context {
    static ThreadLocal<Context> contextThreadLocal = new ThreadLocal<>();

    private static final Context EMPTY = new EmptyContext();

    // identified access user
    private User user;

    private IP ip;

    public static Context current() {
        Context context = contextThreadLocal.get();
        if (context == null) {
            return EMPTY;
        }
        return context;
    }

    /**
     * empty context
     */
    static class EmptyContext extends Context {

    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public IP getIp() {
        return ip;
    }

    public void setIp(IP ip) {
        this.ip = ip;
    }

    public Context attach() {
        Context previous = current();
        contextThreadLocal.set(this);
        return previous;
    }

    public void detach(@Nullable Context context) {
        if (context != EMPTY) {
            contextThreadLocal.set(context);
        } else {
            contextThreadLocal.remove();
        }
    }
}
